<?php

namespace MessageMap\Rabbit;

use MessageMap\Message;
use MessageMap\MsgCenter\MessageMap;
use MessageMap\MsgCenter\SmsMap;
use MessageMap\MsgCenter\TxSmsMap;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

class MsgProducer
{
    /**
     * @var AMQPStreamConnection
     */
    private static $connection = null;

    /**
     * 获取连接
     * @return null|AMQPStreamConnection
     */
    public static function getConnection()
    {
        if (self::$connection === null) {
            $conf = Message::getConf()->getRabbit();
            $connection = new AMQPStreamConnection(
                $conf['host'],
                $conf['port'],
                $conf['username'],
                $conf['password']
            );

            self::$connection = $connection;
        }
        return self::$connection;
    }

    /**
     * 简单发送消息到exchange
     *
     * @param $exchange
     * @param $msgType
     * @param $userId
     * @param $data
     * @param int $time : 毫秒
     * @param string $transferDelayedExchange
     * @param int $transferDelayedKey
     * @return mixed
     */
    public static function sendMsg($exchange, $msgType, $userId, $data, $time = 0, $transferDelayedExchange = '', $transferDelayedKey = 0)
    {
        $userId = empty($userId) ? 0 : $userId;
        // 延时操作替换原来的 exchange 和 route_key
        if (!empty($time)) {
            // 将原来不支持延时功能的消息通过延时队列中转一下
            if (!empty($transferDelayedExchange) && !empty($transferDelayedKey)) {
                // 只有默认的消息路由，才会走 延时转实时 的模式
                $data = [
                    'content' => $data,
                    'real_exchange' => $exchange,
                    'real_route_key' => $msgType,
                    'delay_time' => $time,
                ];
                $exchange = $transferDelayedExchange;
                $msgType = $transferDelayedKey;
            }
        }
        $msg = new AMQPMessage(json_encode([
            'type' => $msgType,
            'user_id' => $userId,
            'timestamp' => time(),
            'data' => $data
        ]), ['delivery_mode' => 2]);
        // 延时操作（延时时间，单位毫秒）
        if (!empty($time)) {
            $headers = new AMQPTable(array("x-delay" => $time)); // 延时时间
            $msg->set('application_headers', $headers); // 设置是否延时
        }
        $channel = self::getConnection()->channel();
        $channel->basic_publish($msg, $exchange);
        return $channel->close();
        //self::getConnection()->channel()->basic_publish($msg, $exchange);
    }


    /**
     * @description 发送登录消息
     * @param int $userId
     * @param array $data
     */
    public static function sendLoginMsg($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_LOGIN, MsgMap::TYPE_LOGIN, $userId, $data);
    }

    /**
     * 发送注册消息
     * @param int $userId
     * @param array $data
     */
    public static function sendRegisterMsg($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_REGISTER, MsgMap::TYPE_REGISTER, $userId, $data);
    }


    /**
     * 发送订单消息
     * @param int $userId
     * @param array $data
     */
    public static function sendOrderMsg($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_ORDER, MsgMap::TYPE_ORDER_SUCCESS, $userId, $data);
    }

    /**
     * 发送订单创建时消息
     * @param int $userId
     * @param array $data
     */
    public static function sendOrderCreateMsg($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_ORDER, MsgMap::TYPE_ORDER_CREATE, $userId, $data);
    }

    /**
     * 发送订单取消消息
     * @param int $userId
     * @param array $data
     */
    public static function sendOrderCancelMsg($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_ORDER, MsgMap::TYPE_ORDER_CANCEL, $userId, $data);
    }

    /**
     * @description 发送退款成功消息
     * @param int $userId
     * @param array $data
     */
    public static function sendRefundMsg($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_REFUND, MsgMap::TYPE_REFUND, $userId, $data);
    }

    /**
     * 腾讯平台发送短信
     * @param int $userId
     * @param int $type 短信类型
     * @param array|string $phone
     * @param int $tpl_id 腾讯平台模板id
     * @param array $params 模板参数
     * @param string $signId
     */
    public static function sendTxSMS($userId, $type, $phone, $tpl_id, $params = [], $signId = TxSmsMap::TX_SIGN_144366)
    {
        $ext = [
            'params' => $params,
            'tpl_id' => $tpl_id,
        ];
        self::sendSMS($userId, $type, SmsMap::SMS_PLATFORM_TX, $phone, TxSmsMap::TX_SIGN_MAP[$signId], $ext);
    }

    /**
     * 通过安信捷平台发送
     * @param int $userId
     * @param int $type 短信类型
     * @param array|string $phone
     * @param string $content
     * @param string $sign 签名，默认【叮咚课堂】
     */
    public static function sendAxjSMS($userId, $type, $phone, $content, $sign = "【心愿圈】")
    {
        self::sendSMS($userId, $type, SmsMap::SMS_PLATFORM_AXJ, $phone, $sign, ['content' => $content]);
    }


    /**
     * 通过阿里云平台发送短信
     * @param int $userId
     * @param int $type
     * @param array|int $phone
     * @param string $tpl_id 模板ID
     * @param array $params
     * @param string $sign 签名，默认【叮咚课堂】
     */
    public static function sendALiYunSMS($userId, $type, $phone, $tpl_id, $params = [], $sign = "心愿圈")
    {
        $ext = [
            'params' => $params,
            'tpl_id' => $tpl_id,
        ];
        self::sendSMS($userId, $type, SmsMap::SMS_PLATFORM_ALIYUN, $phone, $sign, $ext);
    }


    /**
     * 发送短信
     * @param $userId
     * @param $type
     * @param $platform
     * @param string|array $phone 批量用数组
     * @param $sign string 签名
     * @param array $ext
     */
    public static function sendSMS($userId, $type, $platform, $phone, $sign, $ext = [])
    {
        $data = MsgMap::MSG_DATA_STRUCTURE[MsgMap::TYPE_MESSAGE];
        $data['message_type'] = MessageMap::TYPE_SMS;

        $struct = $data['data'][MessageMap::TYPE_SMS];
        foreach ($struct as $k => &$v) {
            if ($k == 'ext') {
                $v = $ext;
                continue;
            }
            if ($k == 'phone' && !is_array($phone)) {
                $v = [$phone];
                continue;
            }
            $v = isset($$k) ? $$k : '';
        }
        $data['data'] = $struct;
        self::sendMsg(MsgMap::EXCHANGE_MESSAGE, MsgMap::TYPE_MESSAGE, $userId, $data);
    }

    /**
     * 微信公众号
     * @param $userId
     * @param $tpl_id string 模板id
     * @param $content array 内容
     * @param string $jump_url 跳转连接
     * @param string $mini_url 跳转小程序
     * @param string $web_oepn_id opend_id
     * @return mixed
     */
    public static function sendWechat($userId, $tpl_id, $content, $jump_url = '', $mini_url = '', $web_oepn_id = '')
    {
        $data = MsgMap::MSG_DATA_STRUCTURE[MsgMap::TYPE_MESSAGE];
        $data['message_type'] = MessageMap::TYPE_WX_TEMPLATE;
        $data['data'] = $data['data'][MessageMap::TYPE_WX_TEMPLATE];
        $data['web_open_id'] = $web_oepn_id;
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k] = $$k; // 根据配置中的key，获取参数中的值
        }
        self::sendMsg(MsgMap::EXCHANGE_MESSAGE, MsgMap::TYPE_MESSAGE, $userId, $data);
    }


    /**
     * 发送微信绑定消息
     */
    public static function sendWechatBind($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_USER_WX_BIND, MsgMap::TYPE_USER_WX_BIND, $userId, $data);
    }


    /**
     * 发送微信关注消息
     */
    public static function sendWechatSubscribe($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_USER_WX_SUBSCRIBE, MsgMap::TYPE_USER_WX_SUBSCRIBE, $userId, $data);
    }


    /**
     * 发送微信取消关注消息
     */
    public static function sendWechatUnsubscribe($userId, $data)
    {
        self::sendMsg(MsgMap::EXCHANGE_USER_WX_UNSUBSCRIBE, MsgMap::TYPE_USER_WX_UNSUBSCRIBE, $userId, $data);
    }











}

